#include <func.h>

//写一个小程序，实现青春版 tree 命令。效果如下：


// tree.c
void dfs_print(const char* path, int width);	/* width: 缩进的空格数目 */

int directories = 0, files = 0;

int main(int argc, char *argv[])
{
    // ./tree dir
    if(argc != 2)
        error(1, 0, "Usage: %s path", argv[0]);

    puts(argv[1]);		// 打印目录的名字

    dfs_print(argv[1], 4);	// 递归打印每一个目录项

    printf("\n%d directories, %d files\n", directories, files);		// 最后打印统计信息
    return 0;
}
void dfs_print(const char* path, int width)
{
    DIR* stream = opendir(path);
    struct dirent* current = 0;
    errno = 0;
    while((current = readdir(stream)) != NULL)
    {

        if(current->d_name[0] == '.')
            continue;

        if(current->d_type == DT_DIR)
        {
            for(int i = 0; i < width; ++i)
                printf(" ");
            directories++;
            printf("%s\n", current->d_name);
            char p[1024];
            sprintf(p, "%s/%s", path, current->d_name);
            dfs_print(p, width + 4);
        }
        else
        {
            for(int i = 0; i < width; ++i)
                printf(" ");
            files++;
            printf("%s\n", current->d_name);
        }
    }

    if(errno)
        error(1, errno, "readdir");

    closedir(stream);
}
